package com.mths.server.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.mths.client.constant.FieldType;
import com.mths.client.dto.MetaParamDTO;
import com.mths.client.util.ListItem;
import com.mths.server.entity.MetaData;
import com.mths.server.entity.MetaDataParam;

@Repository("metaDataDAO")
@Transactional
public class MetaDataDAOImpl extends AbstractDAOImpl<String, MetaData> implements MetaDataDAO {

	@Override
	public List<ListItem> findMetaDataTypeCombo() {
		String sqlStr = "select m.objid, m.fieldName from MetaData m where m.fieldType = :fieldType";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("fieldType", FieldType.COMBOBOX_FIELD);

		List<Object[]> result = (List<Object[]>) query.getResultList();
		List<ListItem> metaList = new ArrayList<ListItem>();
		if (result != null) {
			for (Object[] stringArr : result) {
				String objid = (String) stringArr[0];
				String name = (String) stringArr[1];
				metaList.add(new ListItem(objid, name));
			}
		}
		return metaList;

	}

	@Override
	public MetaDataParam findMetaParamByOid(String objid) {
		String sqlStr = "select m from MetaDataParam m where m.objid = :objid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("objid", objid);

		List<MetaDataParam> result = (List<MetaDataParam>) query.getResultList();
		if (result != null && result.size() == 1) {
			return result.get(0);
		}
		return null;
	}

	@Override
	public void persistOrUpdateParam(MetaDataParam metaDataParam) {
		if (StringUtils.isEmpty(metaDataParam.getObjid()))
			getEntityManager().persist(metaDataParam);
		else
			getEntityManager().merge(metaDataParam);
	}

	@Override
	public List<MetaParamDTO> findMetaParamList(String metaOid) {
		String sqlStr = "select m from MetaDataParam m where m.metaData.objid = :objid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("objid", metaOid);

		List<MetaDataParam> result = (List<MetaDataParam>) query.getResultList();
		List<MetaParamDTO> metaList = new ArrayList<MetaParamDTO>();
		if (result != null) {
			for (MetaDataParam param : result) {
				metaList.add(new MetaParamDTO(param.getObjid(), param.getMetaData().getObjid(), param.getParamKey(), param.getParamValue()));
			}
		}
		return metaList;
	}

	@Override
	public List<MetaData> loadMetaDataByUniquId(String[] uniqueIdArr) {
		String sqlStr = "select m from MetaData m where m.fieldId in (:fieldId)";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("fieldId", Arrays.asList(uniqueIdArr));

		List<MetaData> result = (List<MetaData>) query.getResultList();

		return result;
	}
}
